package com.maimao.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

/**
 * 资源服务器
 *
 * @author MaoLin Wang
 * @date 2020/11/28 10:44 下午
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    private static final String PUBLIC_KEY = "publickey.txt";

    /**
     * 角色继承要在每个资源服务器都进行配置
     *
     * @return
     */
    @Bean
    public RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        String separator = System.lineSeparator();
        StringBuilder hierarchy = new StringBuilder();
        hierarchy.append("ROLE_sys-admin > ROLE_sys-user").append(separator)
                .append(" ROLE_sys-user > ROLE_sys-user-common").append(separator)
                .append("ROLE_sys-admin > ROLE_sys-role").append(separator)
                .append("ROLE_sys-role > ROLE_sysRoleCommon");
        roleHierarchy.setHierarchy(hierarchy.toString());
        return roleHierarchy;
    }

    /**
     * 使用jwt令牌
     */
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    /**
     * 定义JwtAccessTokenConverter 设置jwt的convert，传入公钥
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setVerifierKey(getPubKey());

        return converter;
    }

    /**
     * 获取非对称加密公钥 Key
     *
     * @return 公钥 Key
     */
    private String getPubKey() {
        Resource resource = new ClassPathResource(PUBLIC_KEY);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            return br.lines().collect(Collectors.joining("\n"));
        } catch (IOException ioe) {
            return null;
        }
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //所有请求必须认证通过
        http.authorizeRequests()
                //下边的路径放行
                .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui",
                        "/swagger-resources", "/swagger-resources/configuration/security",
                        "/swagger-ui.html", "/webjars/**",
                        "/actuator/**",
                        "/instance/**",
                        "/sys/user/permissions",
                        "/test/**",
                        "/web/bank/**",
                        "/web/company/checkEmail",
                        "/web/company/register",
                        "/web/code/emailCode",
                        "/web/member/member-register",
                        "/web/member/permissions-g/**",
                        "/web/company/permissions-g/**",
                        "/web/shop/one/mmin",
                        "/web/member/client/**")
                .permitAll()
                .anyRequest().authenticated().and().csrf().disable();
    }


}
